package com.example.daily.ui.screen

import android.util.Log
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Send
import androidx.compose.material.icons.filled.Menu
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.Dialog
import androidx.hilt.navigation.compose.hiltViewModel
import com.example.daily.data.entity.ChatMessage
import com.example.daily.ui.viewmodel.AiConsultViewModel
import java.text.SimpleDateFormat
import java.util.*

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun AiConsultScreen(
    viewModel: AiConsultViewModel = hiltViewModel()
) {
    val messages by viewModel.messages?.collectAsState(initial = emptyList()) ?: remember { mutableStateOf(emptyList()) }
    val messageInput by viewModel.messageInput.collectAsState()
    val foodRecords by viewModel.foodRecords.collectAsState()
    var showQuickMenu by remember { mutableStateOf(false) }

    Log.d("AiConsultScreen", "食物记录数量: ${foodRecords.size}")


    Column(
        modifier = Modifier
            .fillMaxSize()
            .padding(16.dp)
    ) {
        // 消息列表
        LazyColumn(
            modifier = Modifier
                .weight(1f)
                .fillMaxWidth(),
            reverseLayout = true
        ) {
            items(messages) { message ->
                ChatMessageItem(message)
                Spacer(modifier = Modifier.height(8.dp))
            }
        }

        // 输入区域
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(top = 8.dp),
            verticalAlignment = Alignment.CenterVertically
        ) {
            // 快速引用菜单按钮
            IconButton(
                onClick = { 
                    Log.d("AiConsultScreen", "点击快速引用按钮")
                    showQuickMenu = true 
                }
            ) {
                Icon(
                    imageVector = Icons.Default.Menu,
                    contentDescription = "快速引用"
                )
            }
            
            TextField(
                value = messageInput,
                onValueChange = viewModel::onMessageInputChange,
                modifier = Modifier
                    .weight(1f)
                    .padding(horizontal = 8.dp),
                placeholder = { Text("输入您的问题...") },
                maxLines = 3
            )
            
            IconButton(
                onClick = viewModel::sendMessage,
                enabled = messageInput.isNotBlank()
            ) {
                Icon(
                    imageVector = Icons.Default.Send,
                    contentDescription = "发送"
                )
            }
        }
    }

    // 快速引用菜单
    if (showQuickMenu) {
        Log.d("AiConsultScreen", "显示快速引用菜单")
        Dialog(
            onDismissRequest = { 
                Log.d("AiConsultScreen", "关闭快速引用菜单")
                showQuickMenu = false 
            }
        ) {
            Surface(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(16.dp),
                shape = MaterialTheme.shapes.medium,
                color = MaterialTheme.colorScheme.surface
            ) {
                Column(
                    modifier = Modifier.padding(16.dp)
                ) {
                    Text("快速引用", style = MaterialTheme.typography.titleLarge)
                    Spacer(modifier = Modifier.height(16.dp))

                    // 食物记录
                    Text(
                        text = "今日食物记录",
                        style = MaterialTheme.typography.titleMedium,
                        modifier = Modifier.padding(bottom = 8.dp)
                    )
                    if (foodRecords.isEmpty()) {
                        Text("今日暂无食物记录")
                    } else {
                        foodRecords.forEach { record ->
                            TextButton(
                                onClick = {
                                    viewModel.appendToMessage(
                                        "食物记录：${record.foodName} (${record.calories}卡路里)"
                                    )
                                    showQuickMenu = false
                                },
                                modifier = Modifier.fillMaxWidth()
                            ) {
                                Text("${record.foodName} (${record.calories}卡路里)")
                            }
                        }
                    }

                    Spacer(modifier = Modifier.height(16.dp))
                    TextButton(
                        onClick = { showQuickMenu = false },
                        modifier = Modifier.align(Alignment.End)
                    ) {
                        Text("关闭")
                    }
                }
            }
        }
    }
}

@Composable
fun ChatMessageItem(message: ChatMessage) {
    val backgroundColor = if (message.isUser) {
        MaterialTheme.colorScheme.primaryContainer
    } else {
        MaterialTheme.colorScheme.secondaryContainer
    }

    Column(
        modifier = Modifier
            .fillMaxWidth()
            .padding(vertical = 4.dp)
    ) {
        Surface(
            shape = MaterialTheme.shapes.medium,
            color = backgroundColor,
            modifier = Modifier.align(
                if (message.isUser) Alignment.End else Alignment.Start
            )
        ) {
            Text(
                text = message.content,
                style = MaterialTheme.typography.bodyLarge,
                modifier = Modifier.padding(8.dp)
            )
        }
    }
} 